﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

namespace xlsx2const
{
    class ReaderCommon
    {
        private static IEnumerable<SharedStringItem> items = null;

        // xlsxドキュメントを読み込みます
        public static SpreadsheetDocument getDoc(string fullPath)
        {
            SpreadsheetDocument doc = SpreadsheetDocument.Open(fullPath, false);
            items = doc.WorkbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>();
            return doc;
        }

        // WorkbookPartを取得します
        public static WorkbookPart getWbPart(SpreadsheetDocument document)
        {
            return document.WorkbookPart;
        }

        // シート名の一覧を取得します
        public static List<string> getSheetList(SpreadsheetDocument document, WorkbookPart  wbPart){
            List<string> sheetNames = new List<string>();
            if (document == null) 
            {
                return sheetNames;
            }
            // 全シートをループし、シート名を取得
            foreach(Sheet sheet in wbPart.Workbook.Descendants<Sheet>()) 
            {
                sheetNames.Add(sheet.Name);
            }
            return sheetNames;
        }

        //セルの値を取得する
        public static string getCellValue(WorksheetPart wsPart, string cellName) {
            
            var cells = wsPart.Worksheet.Descendants<Cell>();
            Cell cell = cells.Where(c => c.CellReference == cellName).FirstOrDefault();
            
            if ((cell == null) || (cell.CellValue == null)) {
                return "";
            }
            
            string innerText = cell.CellValue.Text;
            
            if ((cell.DataType == null)
                || (cell.DataType.Value != CellValues.SharedString)) {
                return innerText;
            }
            
            // Cellの値を頼りにSharedStringItemを引っ張り出す
            int targetIndex = 0;
            
            if (!Int32.TryParse(innerText, out targetIndex)) {
                return innerText;
            }
            
            SharedStringItem item = items.ElementAt(targetIndex);
            
            return item.FirstChild.InnerText;
        }

        // セルが空orNULLならtrue
        public static bool isEmpty(string x) {
            if (x == null || x.Length == 0) return true;
            return false;
        }
    }
}
